import os
import pathlib
from collections.abc import Sequence

import pandas as pd

__all__ = ["SheetColumnsExtractor"]


class SheetColumnsExtractor(object):
    """
    Unmarshaler for sheet data.

    This unmarshaler is used to unmarshal columns from a sheet. The returned value is a list of tuples, where each tuple
    contains the record with the specified columns.
    """

    path: os.PathLike
    columns: Sequence[str]

    def __init__(self, *, path: os.PathLike, columns: Sequence[str]) -> None:
        self.path = path
        if not columns:
            raise ValueError("Columns must be specified")
        self.columns = columns

    def extract(self) -> Sequence[tuple]:
        """
        Unmarshal the sheet data.

        Returns:
            A list of tuples, where each tuple contains the record with the specified columns.
        """

        # Check if the file exists
        path = pathlib.Path(self.path)
        if not path.exists():
            raise FileNotFoundError(f"File {path} does not exist")

        # Read the sheet data
        frame: pd.DataFrame
        match path.suffix:
            case ".xlsx" | ".xls":
                frame = pd.read_excel(path)
            case ".csv":
                frame = pd.read_csv(path)
            case _:
                raise ValueError(f"Unsupported file extension: {path.suffix}")
        frame.dropna(subset=self.columns, inplace=True)

        # Transform the `DataFrame` into a list of tuples
        result = []
        column_data = (frame[column].to_list() for column in self.columns)
        for v in zip(*column_data):
            result.append(v)
        return result
